/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, DatePicker, Form, Input, InputNumber, Modal, notification, Select, Upload} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormField, FormLayout, ModalFooter} from "antd-extra";
import ViewTitle from "../../../components/ViewTitle";
import notify from "../../../components/NotificationExtra";

moment.locale('zh-cn');
const table = 'SalesOrder';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            store
          }) => ({...user, ...material, ...dynamicLabel, ...global, ...store}))
export default class ModalAddOrEditRentProd extends FormBase {
  constructor(props) {
    super(props);
    this.state = undefined;
  }

  componentDidMount() {

  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {invoicingDate} = values;
              if (invoicingDate) {
                values.invoicingDate = moment(invoicingDate).valueOf();
              }

              const {addMaterials = [], fileList = []} = this.state;
              if (fileList.length === 0) {
                notify({type: 'error', message: "请上传包装标识"});
                return;
              }

              values.fileList = fileList;

              callback(values);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  picHandleCancel = () => this.setState({previewVisible: false});
  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    const temp = this.state;

    temp['previewImage'] = file.url || file.preview;
    temp['previewVisible'] = true;
    this.setState({...temp});
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };

  render() {
    const {form, values, cols = 3} = this.props;
    if (this.state === undefined || this.state === null) {
      this.state = {...values};
      this.state.addMaterials = values && values.materials ? values.materials : [];
    }
    const {previewVisible, previewImage, fileList = []} = this.state;
    const model = this.props[`${table}Model`];
    if (!model) return;

    const {
      prodName,
      prodCode,
      price = 0,
      count = 0,
      pkgFee = 0,
      laborFee = 0,
      taxDeductionPointForLaborCosts = 0,
      invoicingDate,
      deliverWay,
      needInvoice = '是',
      deliverChannel,
      label,
      pkg,
      addMaterials = []
    } = this.state;

    return (
      <div>
        <FormLayout form={form} cols={cols}>
          <FormField
            label={'品名'}
            name={'prodName'}
            required={true}
            initialValue={prodName}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'编号'}
            name={'prodCode'}
            required={true}
            initialValue={prodCode}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'重量（KG)'}
            name={'count'}
            required={true}
            initialValue={count}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'售价'}
            name={'price'}
            required={true}
            initialValue={price}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'标签'}
            name={'label'} initialValue={label}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装'}
            name={'pkg'} initialValue={pkg}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装费用'}
            name={'pkgFee'} initialValue={pkgFee}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'劳务费用'}
            name={'laborFee'}
            initialValue={laborFee}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'劳务扣税点'}
            name={'taxDeductionPointForLaborCosts'}
            initialValue={taxDeductionPointForLaborCosts}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'发货方式'}
            name={'deliverWay'} initialValue={deliverWay}
          >
            <Select style={{width: '100%'}}>
              {this.getSelectOption(model && model.deliverWay ? model.deliverWay.options : [])}
            </Select>
          </FormField>
          <FormField
            label={'开票日期'}
            name={'invoicingDate'}
            initialValue={invoicingDate ? moment(invoicingDate) : undefined}
          >
            <DatePicker style={{width: '100%'}}></DatePicker>
          </FormField>
          <FormField
            label={'是否需要开票'}
            name={'needInvoice'}
            initialValue={needInvoice}
          >
            <Select style={{width: '100%'}}>
              <Option value={'是'}>是</Option>
              <Option value={'否'}>否</Option>
            </Select>
          </FormField>
        </FormLayout>

        <ViewTitle
          title={'包装标识'}
        ></ViewTitle>

        <div style={{marginLeft: '64px'}}>
          <Upload
            action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
            listType="picture-card"
            fileList={fileList}
            accept={".png,.jpg"}
            onPreview={this.picHandlePreview}
            onChange={this.picHandleChange}
            onDownload={file => {
              console.log('ondownlad', file);
            }}
            beforeUpload={(file, fileList) => {
              const isLt2M = file.size / 1024 / 1024 < 2;
              console.log('file size',file.size,isLt2M);
              if (!isLt2M) {
                notify({type: 'error', message: '文件过大！'});
                return isLt2M;
              }
              return false;
            }}
          >
            {this.getUploadPicButton()}
          </Upload>
          <Modal visible={previewVisible} footer={null} onCancel={this.picHandleCancel}>
            <img alt="example" style={{width: '100%'}} src={previewImage}/>
          </Modal>
        </div>

        {
          this.renderFoot()
        }
      </div>

    );
  }
}

